SHELL = /bin/bash
DOCS_DIR = $(realpath .)/sources
SPHINX_TEMPLATE = $(realpath .)/sphinx_template
HTML_OUTPUT_DIR = $(realpath .)/output/html
TAGS_OUTPUT = $(realpath .)/output/tags

# Which documentation to build. Use like this: make SOURCE=<id>
SOURCE=

${SOURCE}:
	@ # Do not print commands
	
	# Get docs info from JSON file to an array
	readarray -t DOCS < <(
		jq --raw-output --arg id $@ \
		   '.[] | select(.id == $$id) | .id, .name, .repository, .sphinx_dir, .tags' \
		   documentation.json
	)
	
	# Extract properties from array to named variable
	DOCS_ID=$${DOCS[0]}
	DOCS_NAME=$${DOCS[1]}
	DOCS_REPOSITORY=$${DOCS[2]}
	DOCS_SPHINXDIR=$${DOCS[3]}
	DOCS_TAGS=$${DOCS[4]}
	
	# Download source file (repository) if first time
	mkdir --parents ${DOCS_DIR}
	
	if [ ! -d "${DOCS_DIR}/$${DOCS_ID}" ]
	then
		git clone "$${DOCS_REPOSITORY}" "${DOCS_DIR}/$${DOCS_ID}"
	fi
	
	# Enter directory with source files
	cd "${DOCS_DIR}/$${DOCS_ID}"
	
	# Find tags to process
	releases=$$(git tag | grep -E "$${DOCS_TAGS}")
	
	# For every tag...
	for release in $${releases}
	do
		echo "Switching to tag: $${release}"
		git checkout $${release}
		
		sphinx-build	-c "${SPHINX_TEMPLATE}" \
				-b dirhtml \
				-D project="$${DOCS_NAME}" \
				-D release="$${release}" \
				"$${DOCS_SPHINXDIR}" \
				"${HTML_OUTPUT_DIR}/$${DOCS_ID}/$${release}"
	done
	
	# Convert the list of tags to a JSON array
	releases=$$(echo "$${releases}" | jq --raw-input '[.]' | jq --slurp --compact-output 'add')
	
	# Create list of tags
	TAGS_LIST=$$(echo '[]' | jq --argjson rel $${releases} --arg id $${DOCS_ID} '. + [{ "id": $$id, "rel": $$rel }]')
	
	# Put list of tags to file
	mkdir --parents ${TAGS_OUTPUT}
	echo "$${TAGS_LIST}" > "${TAGS_OUTPUT}/$${DOCS_ID}.json"

help:
	@echo "Usage: make SOURCE=<id>"

clean:
	rm --recursive --force sources output

.ONESHELL:
.SUFFIXES:
.PHONY: ${SOURCE} clean help
.DELETE_ON_ERROR:
